<script setup lang="ts">
import { onMounted, ref, watch } from 'vue'
import {
  cancelConsultOrderService,
  deleteOrderService,
  getConsultOrderDetailService,
} from '@/api/consult'
import type { ConsultOrderItem } from '@/types/consult'
import { useRoute, useRouter } from 'vue-router'
import { illnessTime, consultHistory } from '@/utils/const'
import { OrderType } from '@/enums'
import { Dialog, Toast } from 'vant'
import { useClipboard } from '@vueuse/core'
import CpPaySheet from '@/components/CpPaySheet.vue'
import { useShowPrescription } from '@/composables/showPrescription'

const route = useRoute()
const orderDetail = ref<ConsultOrderItem>()
const getOrderDetail = async () => {
  const res = await getConsultOrderDetailService(route.params.id as string)
  orderDetail.value = res
}
onMounted(() => {
  getOrderDetail()
})

// 取消问诊
const loading = ref(false) // 防止重复点击
const cancelConsult = async (item: ConsultOrderItem) => {
  loading.value = true
  Dialog.confirm({
    title: '温馨提示',
    message: '您确定要取消问诊吗？',
  })
    .then(async () => {
      try {
        await cancelConsultOrderService(item.id)
        Toast.success({
          message: '取消成功',
        })
        // 刷新列表开销有点大，这里选择局部修改
        item.status = OrderType.ConsultCancel
        item.statusValue = '已取消'
      } catch (error) {
        console.log(error)
      } finally {
        loading.value = false
      }
    })
    .catch(() => {
      // 取消取消请求
      console.log('点击了取消')
      loading.value = false
    })
}

// 删除订单
const router = useRouter()
const deleteOrder = async (item: ConsultOrderItem) => {
  Dialog.confirm({
    title: '温馨提示',
    message: '您确定要删除订单吗？',
  })
    .then(async () => {
      try {
        await deleteOrderService(item.id)
        Toast.success('删除成功')
        const timer = setTimeout(() => {
          router.back()
          clearTimeout(timer)
        }, 1000)
      } catch (error) {
        console.log(error)
      }
    })
    .catch(() => {
      // 取消删除请求
      console.log('点击了取消')
    })
}

// 查看处方
const { showPrescription } = useShowPrescription()

// 复制订单编号
const { copy, copied, isSupported } = useClipboard()
// 1. 复制回调
const onCopy = () => {
  if (!isSupported.value) Toast.fail('未授权，不支持')
  copy(orderDetail.value?.orderNo || '')
}
// 2. 复制后提示
watch(copied, () => {
  if (copied.value) Toast.success('已复制')
})

// 去支付
const show = ref(false)
const onPay = () => {
  show.value = true
}
</script>

<template>
  <div class="consult-detail-page" v-if="orderDetail">
    <cp-nav-bar title="问诊详情" />
    <div class="detail-head">
      <div class="text">
        <h3>图文问诊 {{ orderDetail?.actualPayment }} 元</h3>
        <span
          class="sta"
          :class="{
            orange: orderDetail?.status === OrderType.ConsultPay,
            green: orderDetail?.status === OrderType.ConsultChat,
          }"
          >{{ orderDetail?.statusValue }}</span
        >
        <p class="tip">服务医生信息</p>
      </div>
      <div class="card">
        <img class="avatar" src="@/assets/avatar-doctor.svg" alt="" />
        <p class="doc">
          <span>极速问诊</span>
          <span>{{ orderDetail?.docInfo?.name || '自动分配医生' }}</span>
        </p>
        <van-icon name="arrow" />
      </div>
    </div>
    <div class="detail-patient">
      <van-cell-group :border="false">
        <van-cell
          title="患者信息"
          :value="`${orderDetail?.patientInfo.name} | ${orderDetail?.patientInfo.genderValue} | ${orderDetail?.patientInfo.age}岁`"
        />
        <van-cell title="患病时长" :value="illnessTime[orderDetail?.illnessTime || 1]" />
        <van-cell title="就诊情况" :value="consultHistory[orderDetail?.consultFlag || 0]" />
        <van-cell title="病情描述" :label="orderDetail?.illnessDesc" />
      </van-cell-group>
    </div>
    <div class="detail-order">
      <h3>订单信息</h3>
      <van-cell-group :border="false">
        <van-cell title="订单编号">
          <template #value>
            <span class="copy" @click="onCopy">复制</span>
            {{ orderDetail?.orderNo }}
          </template>
        </van-cell>
        <van-cell title="创建时间" :value="orderDetail?.createTime" />
        <van-cell title="应付款" :value="`￥${orderDetail?.payment || 0}`" />
        <van-cell title="优惠券" :value="`-￥${orderDetail?.couponDeduction || 0}`" />
        <van-cell title="积分抵扣" :value="`-￥${orderDetail?.pointDeduction || 0}`" />
        <van-cell title="实付款" :value="`￥${orderDetail?.actualPayment || 0}`" class="price" />
      </van-cell-group>
    </div>
    <div class="detail-action van-hairline--top">
      <div class="price">
        <span>需付款</span>
        <span>￥{{ orderDetail?.actualPayment }}</span>
      </div>
      <!-- 1. 待支付：取消问诊+去支付 -->
      <div class="foot" v-if="orderDetail.status === OrderType.ConsultPay">
        <van-button
          class="gray"
          plain
          size="small"
          round
          @click="cancelConsult(orderDetail)"
          :loading="loading"
          >取消问诊</van-button
        >
        <van-button type="primary" plain size="small" round @click="onPay"> 去支付 </van-button>
        <!-- 支付弹层 -->
        <cp-pay-sheet
          :order-id="orderDetail.id"
          v-model:show="show"
          :actual-payment="orderDetail?.actualPayment"
        ></cp-pay-sheet>
      </div>
      <!-- 2. 待接诊：取消问诊+继续沟通 -->
      <div class="foot" v-if="orderDetail.status === OrderType.ConsultWait">
        <van-button
          class="gray"
          plain
          size="small"
          round
          @click="cancelConsult(orderDetail)"
          :loading="loading"
          >取消问诊
        </van-button>
        <van-button type="primary" plain size="small" round :to="`/room?orderId=${orderDetail.id}`">
          继续沟通
        </van-button>
      </div>
      <!-- 3. 咨询中：查看处方（如果开了）+继续沟通 -->
      <div class="foot" v-if="orderDetail.status === OrderType.ConsultChat">
        <van-button
          v-if="orderDetail.prescriptionId"
          class="gray"
          plain
          size="small"
          round
          @click="showPrescription(orderDetail.prescriptionId)"
        >
          查看处方
        </van-button>
        <van-button type="primary" plain size="small" round :to="`/room?orderId=${orderDetail.id}`">
          继续沟通
        </van-button>
      </div>
      <!-- 4. 已完成：更多（查看处方，如果开了，删除订单）+问诊记录+（未评价?写评价:查看评价） -->
      <div class="foot" v-if="orderDetail?.status === OrderType.ConsultComplete">
        <van-button class="gray" plain size="small" round :to="`/room?orderId=${orderDetail?.id}`">
          问诊记录
        </van-button>
        <van-button
          v-if="!orderDetail?.evaluateId"
          type="primary"
          plain
          size="small"
          round
          :to="`/room?orderId=${orderDetail?.id}`"
        >
          去评价
        </van-button>
        <van-button
          v-else
          class="gray"
          plain
          size="small"
          round
          :to="`/room?orderId=${orderDetail?.id}`"
        >
          查看评价
        </van-button>
      </div>
      <!-- 5. 已取消：删除订单+咨询其他医生 -->
      <div class="foot" v-if="orderDetail?.status === OrderType.ConsultCancel">
        <van-button class="gray" plain size="small" round @click="deleteOrder(orderDetail)"
          >删除订单</van-button
        >
        <van-button type="primary" plain size="small" round to="/">咨询其他医生</van-button>
      </div>
    </div>
  </div>

  <div class="consult-detail-page" v-else>
    <cp-nav-bar title="问诊详情" />
    <van-skeleton title :row="4" style="margin-top: 30px" />
    <van-skeleton title :row="4" style="margin-top: 30px" />
  </div>
</template>

<style lang="scss" scoped>
.consult-detail-page {
  padding: 46px 0 110px 0;
}
.detail-head {
  height: 140px;
  position: relative;
  &::before {
    content: '';
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 135px;
    background: linear-gradient(180deg, rgba(44, 181, 165, 0), rgba(44, 181, 165, 0.2));
    border-bottom-left-radius: 150px 20px;
    border-bottom-right-radius: 150px 20px;
  }
  padding: 15px;
  .text {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    padding: 10px 3px;
    .sta {
      color: var(--cp-tag);
      font-weight: 500;
      font-size: 16px;
      &.green {
        color: var(--cp-primary);
      }
      &.orange {
        color: #f2994a;
      }
    }
    .tip {
      width: 100%;
      color: var(--cp-text3);
      margin-top: 5px;
    }
  }
  .card {
    height: 74px;
    background-color: #fff;
    border-radius: 8px;
    position: relative;
    display: flex;
    align-items: center;
    padding: 0 15px;
    box-shadow: 0px 0px 22px 0px rgba(229, 229, 229, 0.5);
    .avatar {
      width: 38px;
      height: 38px;
    }
    .doc {
      flex: 1;
      padding-left: 15px;
      > span {
        display: block;
        font-size: 16px;
        &:last-child {
          font-size: 13px;
          color: var(--cp-text3);
        }
      }
    }
    .van-icon {
      color: var(--cp-tip);
    }
  }
}
.detail-patient {
  &::after {
    content: '';
    display: block;
    height: 12px;
    background-color: var(--cp-bg);
  }
}
.detail-order {
  > h3 {
    padding: 15px 18px;
    font-weight: normal;
  }
  .copy {
    padding: 2px 10px;
    border: 1px solid var(--cp-primary);
    background-color: var(--cp-plain);
    color: var(--cp-primary);
    font-size: 12px;
    border-radius: 12px;
    margin-right: 10px;
  }
  :deep(.van-cell__title) {
    width: 70px;
    flex: none;
  }
  .price :deep(.van-cell__value) {
    font-size: 16px;
    color: var(--cp-price);
  }
}
.detail-action {
  height: 65px;
  width: 100%;
  position: fixed;
  left: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  background-color: #fff;
  justify-content: flex-end;
  padding: 0 15px;
  box-sizing: border-box;
  .price {
    flex: 1;
    > span:last-child {
      font-size: 18px;
      color: var(--cp-price);
      padding-left: 5px;
    }
  }
  .van-button {
    margin-left: 10px;
    padding-left: 17px;
    padding-right: 17px;
  }
  :deep(.van-button--default) {
    background-color: var(--cp-bg);
    color: var(--cp-text3);
  }
}
.van-cell {
  padding-left: 18px;
  padding-right: 18px;
}
</style>
